/**
/**
 * 映射管理模块
 * @author 运费系统团队
 */

function useMappingManagement() {
    const { ref, reactive, watch } = Vue;
    // 响应式数据
    const mappings = ref([]);
    const submitting = ref(false);
    const showAddMappingModal = ref(false);
    const showBatchMappingModal = ref(false);
    
    // 所选策略的映射详情
    const selectedMappingStrategyId = ref('');
    const mappingWeightRules = ref([]);
    const mappingAreaDetails = ref([]);
    const mappingMergedData = ref([]);
    const mappingGroupByAreaData = ref([]); // 新增：按区域分组的数据
    const filteredAssignments = ref([]);
    const selectedAssignment = ref(null);
    
    // 显示模式状态
    const displayMode = ref('by-rule'); // 'by-rule' 或 'by-area'
    
    // 表单的重量规则
    const filteredWeightRules = ref([]);
    const batchWeightRules = ref([]);
    
    const mappingForm = reactive({
        strategyId: '',
        areaId: '',
        segmentRuleIds: [] // 改为数组支持多选
    });
    
    const batchMappingForm = reactive({
        strategyId: '',
        areaIds: [],
        segmentRuleIds: []
    });
    
    // 三级联动多选框状态
    const cascaderState = reactive({
        selectedProvinces: new Set(),
        selectedCities: new Set(), 
        selectedDistricts: new Set(),
        expandedProvinces: new Set(),
        expandedCities: new Set(),
        // 联动功能状态
        isLinkageEnabled: true // 是否启用联动功能
    });
    
    // 省市区数据结构
    const areaTree = ref([]);
    
    // 防止无限循环的状态变量
    const isLoadingAreas = ref(false);
    const areaLoadRetryCount = ref(0);
    const MAX_AREA_LOAD_RETRIES = 3;
    
    // 监听策略选择变化，同步更新表单中的策略ID
    watch(selectedMappingStrategyId, (newStrategyId) => {
        console.log('策略选择变化:', newStrategyId);
        
        // 如果正在显示新增映射模态框，同步更新表单
        if (showAddMappingModal.value && newStrategyId) {
            mappingForm.strategyId = newStrategyId;
            loadWeightRulesForMapping();
        }
        
        // 如果正在显示批量映射模态框，同步更新表单
        if (showBatchMappingModal.value && newStrategyId) {
            batchMappingForm.strategyId = newStrategyId;
            loadWeightRulesForBatch();
        }
    });

    /**
     * 加载所有映射
     */
    const loadMappings = async () => {
        try {
            const result = await window.FreightApp.api.getMappings();
            if (result.code === 0) {
                mappings.value = result.data || [];
                // 如果已选择策略，则重新加载详情
                if (selectedMappingStrategyId.value) {
                    loadMappingDetails();
                }
            } else {
                // API失败时清空数据
                mappings.value = [];
                window.showMessage('加载映射失败: ' + result.msg, true);
            }
        } catch (err) {
            console.error('加载映射失败:', err);
            // 请求异常时清空数据
            mappings.value = [];
            window.showMessage('加载映射失败', true);
        }
    };

    /**
     * 加载所选策略的映射详情
     */
    const loadMappingDetails = async () => {
        if (!selectedMappingStrategyId.value) {
            mappingWeightRules.value = [];
            mappingAreaDetails.value = [];
            mappingMergedData.value = [];
            mappingGroupByAreaData.value = []; // 清空按区域分组数据
            filteredAssignments.value = [];
            return;
        }

        try {
            // 1. 为策略加载重量规则
            const weightRulesResult = await window.FreightApp.api.getWeightRules(selectedMappingStrategyId.value);
            if (weightRulesResult.code === 0) {
                const validRules = (weightRulesResult.data || []).filter(rule => rule != null && rule.id != null);
                mappingWeightRules.value = validRules;
            }

            // 2. 为策略加载映射
            const mappingsResult = await window.FreightApp.api.getMappings(selectedMappingStrategyId.value);
            if (mappingsResult.code === 0) {
                const strategyMappings = mappingsResult.data || [];
                
                // ——————————————————————————————————————————————————————————————————————
                // 3. 从主应用获取区域数据
                const allAreas = window.FreightApp?.getAllAreas?.() || [];
                
                // 按区域分组映射
                const areaMap = new Map();
                strategyMappings.forEach(mapping => {
                    // 从所有区域中查找区域名称
                    const areaInfo = allAreas.find(area => area.id === mapping.areaId);
                    const areaName = areaInfo ? window.formatAreaName(areaInfo) : `区域ID:${mapping.areaId}`;
                    
                    if (!areaMap.has(mapping.areaId)) {
                        areaMap.set(mapping.areaId, {
                            areaId: mapping.areaId,
                            areaName: areaName,
                            mappings: {}
                        });
                    }
                    areaMap.get(mapping.areaId).mappings[mapping.segmentRuleId] = true;
                });

                mappingAreaDetails.value = Array.from(areaMap.values());
                
                // 4. 创建合并数据结构
                const mergedMappings = [];
                (mappingWeightRules.value || []).forEach(rule => {
                    const areasForThisRule = [];
                    
                    (mappingAreaDetails.value || []).forEach(areaDetail => {
                        if (areaDetail.mappings && areaDetail.mappings[rule.id]) {
                            areasForThisRule.push(areaDetail.areaName);
                        }
                    });
                    
                    if (areasForThisRule.length > 0) {
                        mergedMappings.push({
                            ruleId: rule.id,
                            upperBound: rule.upperBound,
                            freight: rule.freight,
                            areas: areasForThisRule,
                            areasDisplay: areasForThisRule
                        });
                    }
                });
                
                mappingMergedData.value = mergedMappings;
                
                // 5. 加载按区域分组的数据
                try {
                    const groupByAreaResult = await window.FreightApp.api.getMappingsGroupByArea({ 
                        strategyId: selectedMappingStrategyId.value 
                    });
                    if (groupByAreaResult.code === 0) {
                        mappingGroupByAreaData.value = groupByAreaResult.data || [];
                        console.log('按区域分组数据加载成功:', mappingGroupByAreaData.value.length, '个区域');
                    } else {
                        console.warn('按区域分组数据加载失败:', groupByAreaResult.msg);
                        mappingGroupByAreaData.value = [];
                    }
                } catch (err) {
                    console.error('加载按区域分组数据失败:', err);
                    mappingGroupByAreaData.value = [];
                }
            }

            // 5. 为策略加载分配
            const assignmentsResult = await window.FreightApp.api.getAssignments({ strategyId: selectedMappingStrategyId.value });
            if (assignmentsResult.code === 0) {
                filteredAssignments.value = assignmentsResult.data || [];
                console.log('策略分配加载成功，数量:', filteredAssignments.value.length, '策略ID:', selectedMappingStrategyId.value);
                
                // 如果没有选中的分配且有分配数据，自动选择第一个
                if (!selectedAssignment.value && filteredAssignments.value.length > 0) {
                    const firstAssignment = filteredAssignments.value[0];
                    selectedAssignment.value = firstAssignment.id;
                    console.log('✅ 自动选择第一个策略分配:', firstAssignment);
                }
            } else {
                console.warn('策略分配加载失败:', assignmentsResult.msg, '策略ID:', selectedMappingStrategyId.value);
                filteredAssignments.value = [];
                selectedAssignment.value = null;
            }
        } catch (err) {
            console.error('加载映射详情失败:', err);
            mappingWeightRules.value = [];
            mappingAreaDetails.value = [];
            mappingMergedData.value = [];
            mappingGroupByAreaData.value = []; // 清空按区域分组数据
            filteredAssignments.value = [];
            selectedAssignment.value = null; // 清空选中的分配
        }
    };

    /**
     * 为单个映射表单加载重量规则
     */
    const loadWeightRulesForMapping = async () => {
        if (!mappingForm.strategyId) {
            console.log('清空重量规则：策略ID为空');
            filteredWeightRules.value = [];
            mappingForm.segmentRuleIds = [];
            return;
        }
        
        try {
            console.log('加载重量规则，策略ID:', mappingForm.strategyId);
            const result = await window.FreightApp.api.getWeightRules(mappingForm.strategyId);
            
            if (result.code === 0 || result.code === '0') {
                const rules = result.data || [];
                console.log('加载到重量规则:', rules.length, '个');
                filteredWeightRules.value = rules;
                
                // 清空之前的选择
                mappingForm.segmentRuleIds = [];
                
                // 如果没有规则，提示用户
                if (rules.length === 0) {
                    console.warn('该策略下没有重量区间规则');
                }
            } else {
                console.error('加载重量规则失败:', result.msg);
                filteredWeightRules.value = [];
                mappingForm.segmentRuleIds = [];
            }
        } catch (err) {
            console.error('加载重量规则异常:', err);
            filteredWeightRules.value = [];
            mappingForm.segmentRuleIds = [];
        }
    };

    /**
     * 为批量映射表单加载重量规则
     */
    const loadWeightRulesForBatch = async () => {
        if (!batchMappingForm.strategyId) {
            batchWeightRules.value = [];
            batchMappingForm.segmentRuleIds = [];
            return;
        }
        try {
            const result = await window.FreightApp.api.getWeightRules(batchMappingForm.strategyId);
            if (result.code === 0) {
                batchWeightRules.value = result.data || [];
            }
        } catch (err) {
            console.error('加载重量规则失败:', err);
        }
    };

    /**
     * 选择分配（仓库 + 物流公司）
     */
    const selectAssignment = (assignment) => {
        selectedAssignment.value = assignment.id;
    };

    /**
     * 添加单个映射
     */
    const addMapping = () => {
        resetMappingForm();
        buildAreaTree(); // 确保区域树已构建
        
        // 如果已选择策略，自动设置到表单中
        if (selectedMappingStrategyId.value) {
            mappingForm.strategyId = selectedMappingStrategyId.value;
            loadWeightRulesForMapping();
        }
        
        showAddMappingModal.value = true;
    };

    /**
     * 提交单个映射
     */
    const submitMapping = async () => {
        // 表单验证
        const validation = validateMappingForm();
        if (!validation.isValid) {
            console.error('映射表单验证失败:', validation.errors);
            window.showMessage(validation.errors[0], true);
            return;
        }
        
        // 参数正确性检查
        if (!mappingForm.segmentRuleIds || mappingForm.segmentRuleIds.length === 0) {
            console.error('重量规则ID列表为空:', mappingForm.segmentRuleIds);
            window.showMessage('请选择至少一个重量区间规则', true);
            return;
        }

        submitting.value = true;
        try {
            // API安全检查
            console.log('🔧 提交映射数据:', {
                strategyId: mappingForm.strategyId,
                areaId: mappingForm.areaId,
                segmentRuleIds: mappingForm.segmentRuleIds,
                segmentRuleIdsLength: mappingForm.segmentRuleIds.length
            });
            
            if (!window.FreightApp.api) {
                console.error('❗️ API对象未正确导入到mapping-management.js');
                throw new Error('API对象未正确初始化，请刷新页面重试');
            }
            
            if (!window.FreightApp.api.addBatchMappings || typeof window.FreightApp.api.addBatchMappings !== 'function') {
                console.error('❌ API方法 addBatchMappings 不存在或不是函数');
                throw new Error('API方法 addBatchMappings 不存在，请检查window.FreightApp.api.js配置');
            }
            
            // 批量创建映射（单区域多重量规则）
            const batchData = {
                strategyId: Number(mappingForm.strategyId),
                areaIds: [Number(mappingForm.areaId)], // 单个区域
                segmentRuleIds: mappingForm.segmentRuleIds.map(id => Number(id)) // 多个重量规则
            };
            
            console.log('🔧 最终提交数据:', batchData);
            
            const result = await window.FreightApp.api.addBatchMappings(batchData);
            
            console.log('🔧 API调用结果:', result);
            
            if (result.code === 0 || result.code === '0') {
                window.showMessage('映射创建成功');
                closeMappingModal();
                loadMappings();
                // 重新加载映射详情
                if (selectedMappingStrategyId.value) {
                    loadMappingDetails();
                }
            } else {
                const errorMsg = result.msg || result.message || '映射创建失败';
                console.error('映射创建失败:', errorMsg);
                window.showMessage(errorMsg, true);
            }
        } catch (err) {
            console.error('❌ 映射提交错误详情:', err);
            
            let errorMessage = '提交失败';
            
            if (err.message.includes('Cannot read properties of undefined')) {
                errorMessage = 'API对象未正确初始化，请刷新页面重试';
            } else if (err.message.includes('is not a function')) {
                errorMessage = 'API方法不存在，请检查系统配置';
            } else if (err.message.includes('重量区间规则ID不能为空')) {
                errorMessage = '请选择至少一个重量区间规则';
            } else {
                errorMessage = err.message || '未知错误';
            }
            
            window.showMessage(`提交失败: ${errorMessage}`, true);
        } finally {
            submitting.value = false;
        }
    };

    /**
     * 添加批量映射
     */
    const addBatchMappings = () => {
        resetBatchMappingForm();
        buildAreaTree(); // 确保区域树已构建
        
        // 如果已选择策略，自动设置到表单中
        if (selectedMappingStrategyId.value) {
            batchMappingForm.strategyId = selectedMappingStrategyId.value;
            loadWeightRulesForBatch();
        }
        
        showBatchMappingModal.value = true;
    };

    /**
     * 提交批量映射
     */
    const submitBatchMapping = async () => {
        const validation = validateBatchMappingForm();
        if (!validation.isValid) {
            window.showMessage(validation.errors[0], true);
            return;
        }

        submitting.value = true;
        try {
            // API安全检查
            console.log('🔧 提交批量映射数据:', batchMappingForm);
            console.log('🔧 API对象:', window.FreightApp.api);
            
            if (!window.FreightApp.api) {
                console.error('❗️ API对象未正确导入到mapping-management.js');
                throw new Error('API对象未正确初始化，请刷新页面重试');
            }
            
            if (!window.FreightApp.api.addBatchMappings || typeof window.FreightApp.api.addBatchMappings !== 'function') {
                console.error('❌ API方法 addBatchMappings 不存在或不是函数');
                throw new Error('API方法 addBatchMappings 不存在，请检查window.FreightApp.api.js配置');
            }
            
            const result = await window.FreightApp.api.addBatchMappings(batchMappingForm);
            
            console.log('🔧 API调用结果:', result);
            
            if (result.code === 0) {
                window.showMessage('批量创建成功');
                closeBatchMappingModal();
                loadMappings();
            } else {
                window.showMessage(result.msg || '批量创建失败', true);
            }
        } catch (err) {
            console.error('❌ 批量映射提交错误详情:', err);
            
            let errorMessage = '提交失败';
            
            if (err.message.includes('Cannot read properties of undefined')) {
                errorMessage = 'API对象未正确初始化，请刷新页面重试';
            } else if (err.message.includes('is not a function')) {
                errorMessage = 'API方法不存在，请检查系统配置';
            } else {
                errorMessage = err.message || '未知错误';
            }
            
            window.showMessage(`提交失败: ${errorMessage}`, true);
        } finally {
            submitting.value = false;
        }
    };

    /**
     * 删除多个区域的映射规则
     */
    const deleteMappingRuleForAreas = async (areas, segmentRuleId) => {
        const areaCount = areas.length;
        if (!confirm(`确定要删除这${areaCount}个区域的映射规则吗？`)) return;

        try {
            const mappingIdsToDelete = [];
            const errors = [];

            for (const areaName of areas) {
                const areaDetail = (mappingAreaDetails.value || []).find(detail => detail.areaName === areaName);
                if (!areaDetail) {
                    errors.push(`未找到区域：${areaName}`);
                    continue;
                }

                const mapping = (mappings.value || []).find(m =>
                    m.areaId === areaDetail.areaId &&
                    m.segmentRuleId === segmentRuleId &&
                    m.strategyId === selectedMappingStrategyId.value
                );

                if (!mapping) {
                    errors.push(`未找到${areaName}的映射记录`);
                    continue;
                }

                mappingIdsToDelete.push(mapping.id);
            }

            // 使用批量删除接口
            if (mappingIdsToDelete.length > 0) {
                console.log('🗑️ mapping-management 批量删除映射，ID列表:', mappingIdsToDelete);
                const result = await window.FreightApp.api.batchDeleteMappings(mappingIdsToDelete);
                if (result.code === 0) {
                    const deleteCount = result.data;
                    window.showMessage(`成功删除${deleteCount}个映射`);
                    loadMappings();
                    loadMappingDetails();
                } else {
                    window.showMessage(result.msg || '批量删除失败', true);
                }
            }

            if (errors.length > 0) {
                window.showMessage(`部分删除失败：${errors.join('；')}`, true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        }
    };

    /**
     * 关闭映射模态框
     */
    const closeMappingModal = () => {
        showAddMappingModal.value = false;
        resetMappingForm();
    };

    /**
     * 关闭批量映射模态框
     */
    const closeBatchMappingModal = () => {
        showBatchMappingModal.value = false;
        resetBatchMappingForm();
    };

    /**
     * 重置映射表单
     */
    const resetMappingForm = () => {
        Object.assign(mappingForm, {
            strategyId: '',
            areaId: '',
            segmentRuleIds: [] // 重置为空数组
        });
        filteredWeightRules.value = [];
        
        // 也清除区域选择状态，确保新增映射时不会受到批量映射的影响
        cascaderState.selectedProvinces.clear();
        cascaderState.selectedCities.clear();
        cascaderState.selectedDistricts.clear();
        cascaderState.expandedProvinces.clear();
        cascaderState.expandedCities.clear();
    };

    /**
     * 重置批量映射表单
     */
    const resetBatchMappingForm = () => {
        Object.assign(batchMappingForm, {
            strategyId: '',
            areaIds: [],
            segmentRuleIds: []
        });
        batchWeightRules.value = [];
        
        // 清除三级联动选择状态
        cascaderState.selectedProvinces.clear();
        cascaderState.selectedCities.clear();
        cascaderState.selectedDistricts.clear();
        cascaderState.expandedProvinces.clear();
        cascaderState.expandedCities.clear();
        
        console.log('批量映射表单已重置，清除了所有区域选择状态');
    };

    /**
     * 验证映射表单
     */
    const validateMappingForm = () => {
        const errors = [];
        
        if (!mappingForm.strategyId) {
            errors.push('请选择策略');
        }
        
        if (!mappingForm.areaId) {
            errors.push('请选择区域');
        }
        
        // 检查重量规则选择
        console.log('验证映射表单 - 重量规则数量:', filteredWeightRules.value.length, '已选择规则:', mappingForm.segmentRuleIds.length);
        
        if (filteredWeightRules.value.length === 0) {
            errors.push('该策略下没有可用的重量区间规则，请先添加重量规则');
        } else if (mappingForm.segmentRuleIds.length === 0) {
            errors.push('请至少选择一个重量区间规则');
        }

        return {
            isValid: errors.length === 0,
            errors
        };
    };

    /**
     * 验证批量映射表单
     */
    const validateBatchMappingForm = () => {
        const errors = [];
        
        if (!batchMappingForm.strategyId) errors.push('请选择策略');
        if (batchMappingForm.areaIds.length === 0) errors.push('请至少选择一个区域');
        if (batchMappingForm.segmentRuleIds.length === 0) errors.push('请至少选择一个重量规则');

        return {
            isValid: errors.length === 0,
            errors
        };
    };

    /**
     * 切换联动状态
     */
    const toggleLinkage = () => {
        cascaderState.isLinkageEnabled = !cascaderState.isLinkageEnabled;
        console.log('🔗 联动状态切换:', cascaderState.isLinkageEnabled ? '已启用' : '已禁用');
    };

    /**
     * 获取重量规则名称
     */
    const getWeightRuleName = (segmentRuleId) => {
        const rule = (mappingWeightRules.value || []).find(r => r.id === segmentRuleId);
        return rule ? `≤${rule.upperBound}kg, ${rule.freight}元` : '未知规则';
    };

    /**
     * 初始化区域树结构
     */
    const buildAreaTree = () => {
        // 从全局应用实例获取区域数据
        let allAreas = [];
        
        // 优先从Vue应用实例的areas属性获取
        if (window.vueAppInstance?.areas?.value) {
            allAreas = window.vueAppInstance.areas.value;
        } else if (window.vueAppInstance?.areas) {
            allAreas = window.vueAppInstance.areas;
        } else if (window.FreightApp?.getAllAreas) {
            allAreas = window.FreightApp.getAllAreas();
        }
        
        // 如果没有数据，直接返回，不使用模拟数据
        if (allAreas.length === 0) {
            console.warn('mapping: 无法获取区域数据，区域选择器将显示为空');
            areaTree.value = [];
            return;
        }
        
        console.log('mapping buildAreaTree开始，原始区域数据:', allAreas);
        
        // 数据预处理：确保有省级数据
        const processedAreas = preprocessMappingAreaData(allAreas);
        console.log('mapping buildAreaTree预处理后，区域数据:', processedAreas);
        
        const tree = [];
        // 使用更强的去重机制
        const uniqueProvinces = new Map();
        const uniqueCities = new Map();
        const uniqueDistricts = new Map();
        
        // 按层级分组数据，并进行去重
        processedAreas.forEach(area => {
            if (area.level === 1) {
                // 省级去重：使用provinceCode作为唯一标识
                const provinceKey = area.provinceCode;
                if (!uniqueProvinces.has(provinceKey)) {
                    const province = {
                        id: area.id,
                        code: area.provinceCode,
                        name: area.provinceName,
                        level: 1,
                        children: []
                    };
                    uniqueProvinces.set(provinceKey, province);
                    tree.push(province);
                }
            } else if (area.level === 2) {
                // 市级去重：使用provinceCode+cityCode作为唯一标识
                const cityKey = `${area.provinceCode}|${area.cityCode}`;
                const provinceKey = area.provinceCode;
                
                if (!uniqueCities.has(cityKey)) {
                    const province = uniqueProvinces.get(provinceKey);
                    if (province) {
                        const city = {
                            id: area.id,
                            code: area.cityCode,
                            name: area.cityName,
                            provinceCode: area.provinceCode,
                            level: 2,
                            children: []
                        };
                        uniqueCities.set(cityKey, city);
                        province.children.push(city);
                    } else {
                        console.warn('mapping: 找不到对应的省份数据:', area.provinceCode, area);
                    }
                }
            } else if (area.level === 3) {
                // 区县级去重：使用provinceCode+cityCode+districtCode作为唯一标识
                const districtKey = `${area.provinceCode}|${area.cityCode}|${area.districtCode}`;
                const cityKey = `${area.provinceCode}|${area.cityCode}`;
                
                if (!uniqueDistricts.has(districtKey)) {
                    const city = uniqueCities.get(cityKey);
                    if (city) {
                        const district = {
                            id: area.id,
                            code: area.districtCode,
                            name: area.districtName,
                            provinceCode: area.provinceCode,
                            cityCode: area.cityCode,
                            level: 3
                        };
                        uniqueDistricts.set(districtKey, district);
                        city.children.push(district);
                    } else {
                        console.warn('mapping: 找不到对应的城市数据:', area.cityCode, '省份:', area.provinceCode, area);
                    }
                }
            }
        });
        
        areaTree.value = tree;
        console.log('mapping buildAreaTree完成，区域数据:', processedAreas.length, '构建树节点:', tree.length);
        console.log('mapping 构建的区域树结构:', tree);
        console.log('mapping 去重统计 - 省份:', uniqueProvinces.size, '城市:', uniqueCities.size, '区县:', uniqueDistricts.size);
        
        // 如果没有数据且未超过重试次数，尝试重新加载
        if (tree.length === 0 && !isLoadingAreas.value && areaLoadRetryCount.value < MAX_AREA_LOAD_RETRIES) {
            console.log(`区域树为空，尝试第${areaLoadRetryCount.value + 1}次重新加载区域数据...`);
            isLoadingAreas.value = true;
            areaLoadRetryCount.value++;
            
            setTimeout(() => {
                if (window.vueAppInstance?.loadAreas) {
                    window.vueAppInstance.loadAreas().then(() => {
                        console.log('重新加载区域数据后，再次构建区域树...');
                        buildAreaTree();
                        isLoadingAreas.value = false;
                    }).catch((err) => {
                        console.error('加载区域数据失败:', err);
                        isLoadingAreas.value = false;
                    });
                } else {
                    console.error('未找到全局loadAreas方法');
                    isLoadingAreas.value = false;
                }
            }, 200);
        } else if (tree.length === 0 && areaLoadRetryCount.value >= MAX_AREA_LOAD_RETRIES) {
            console.warn('已达到最大重试次数，停止重新加载区域数据');
        }
    };
    
    /**
     * 映射管理模块的区域数据预处理
     */
    const preprocessMappingAreaData = (areas) => {
        console.log('mapping 开始数据预处理，原始数据:', areas);
        
        const result = [...areas];
        const existingProvinceCodes = new Set();
        const neededProvinces = new Set();
        
        // 收集现有的省级数据
        areas.forEach(area => {
            if (area.level === 1) {
                existingProvinceCodes.add(area.provinceCode);
            } else if (area.level >= 2) {
                neededProvinces.add(area.provinceCode);
            }
        });
        
        console.log('mapping 现有省级数据:', Array.from(existingProvinceCodes));
        console.log('mapping 需要省级数据:', Array.from(neededProvinces));
        
        // 为缺少的省级数据创建虚拟省份节点
        neededProvinces.forEach(provinceCode => {
            if (!existingProvinceCodes.has(provinceCode)) {
                console.log('mapping 为省份编码创建虚拟省级数据:', provinceCode);
                
                // 从现有数据中找到第一个该省份的数据来获取省份名称
                const sampleArea = areas.find(area => area.provinceCode === provinceCode);
                if (sampleArea) {
                    const virtualProvince = {
                        id: `virtual_mapping_${provinceCode}`, // 使用虚拟ID
                        level: 1,
                        provinceCode: provinceCode,
                        provinceName: sampleArea.provinceName,
                        provinceShortName: sampleArea.provinceShortName || sampleArea.provinceName,
                        cityCode: null,
                        cityName: null,
                        districtCode: null,
                        districtName: null
                    };
                    result.push(virtualProvince);
                    console.log('mapping 创建虚拟省级数据:', virtualProvince);
                }
            }
        });
        
        // 按层级排序，确保省级数据优先处理
        const sortedResult = result.sort((a, b) => a.level - b.level);
        console.log('mapping 数据预处理完成，最终数据:', sortedResult);
        
        return sortedResult;
    };
    
    /**
     * 获取Mock区域数据作为fallback
     * 注意：根据用户要求，不再使用模拟数据
     */
    const getMockAreaData = () => {
        // 已废弃：不再使用模拟数据
        return [];
    };

    /**
     * 切换省份选择
     */
    const toggleProvinceSelection = (province) => {
        console.log('🟩 [PROVINCE] toggleProvinceSelection triggered for:', province?.name);
        
        // 添加安全检查
        if (!province || !province.id || !province.children) {
            console.error('无效的省份数据:', province);
            return;
        }
        
        const isProvinceSelected = cascaderState.selectedProvinces.has(province.id);
        
        // 统计当前选中的城市和区县数量
        let selectedCityCount = 0;
        let selectedDistrictCount = 0;
        let totalCityCount = province.children.length;
        let totalDistrictCount = 0;
        
        province.children.forEach(city => {
            if (city && city.id) {
                if (cascaderState.selectedCities.has(city.id)) {
                    selectedCityCount++;
                }
                if (city.children) {
                    totalDistrictCount += city.children.length;
                    selectedDistrictCount += city.children.filter(district => 
                        district && district.id && cascaderState.selectedDistricts.has(district.id)
                    ).length;
                }
            }
        });
        
        const hasAnyChildSelected = selectedCityCount > 0 || selectedDistrictCount > 0;
        const isFullySelected = isProvinceSelected && 
                               selectedCityCount === totalCityCount && 
                               selectedDistrictCount === totalDistrictCount;
        
        console.log(`省份 ${province.name} 状态: 省份选中=${isProvinceSelected}, 城市选中=${selectedCityCount}/${totalCityCount}, 区县选中=${selectedDistrictCount}/${totalDistrictCount}`);
        
        if (isFullySelected) {
            // 当前是完全选中状态（省份+所有子级），切换为只选择省份
            console.log(`切换为只选择省份: ${province.name}`);
            cascaderState.selectedProvinces.add(province.id);
            
            // 取消选择所有子级城市和区县
            province.children.forEach(city => {
                if (city && city.id) {
                    cascaderState.selectedCities.delete(city.id);
                    if (city.children) {
                        city.children.forEach(district => {
                            if (district && district.id) {
                                cascaderState.selectedDistricts.delete(district.id);
                            }
                        });
                    }
                }
            });
        } else if (isProvinceSelected && !hasAnyChildSelected) {
            // 当前只选择了省份（无子级），取消省份选择
            console.log(`取消选择省份: ${province.name}`);
            cascaderState.selectedProvinces.delete(province.id);
        } else if (isProvinceSelected && hasAnyChildSelected) {
            // 省份已选中且有部分子级选中，取消全部选择
            console.log(`取消选择省份及所有子级: ${province.name}`);
            cascaderState.selectedProvinces.delete(province.id);
            
            // 取消选择所有子级城市和区县
            province.children.forEach(city => {
                if (city && city.id) {
                    cascaderState.selectedCities.delete(city.id);
                    if (city.children) {
                        city.children.forEach(district => {
                            if (district && district.id) {
                                cascaderState.selectedDistricts.delete(district.id);
                            }
                        });
                    }
                }
            });
        } else {
            // 省份未选中，首次选择：只选择省份本身
            console.log(`首次选择省份: ${province.name}`);
            cascaderState.selectedProvinces.add(province.id);
            // 不自动选择子级城市和区县
        }
        
        updateSelectedAreaIds();
        console.log('省份选择完成，已选区域数量:', getSelectedAreaTags().length);
    };

    /**
     * 切换城市选择
     */
    const toggleCitySelection = (city, province) => {
        console.log('🟦 [CITY] toggleCitySelection triggered for:', city?.name, 'in', province?.name);
        
        // 添加安全检查
        if (!city || !city.id || !city.children || !province || !province.id) {
            console.error('无效的城市或省份数据:', city, province);
            return;
        }
        
        const isCitySelected = cascaderState.selectedCities.has(city.id);
        
        // 统计当前选中的区县数量
        const selectedDistrictCount = city.children.filter(district => 
            district && district.id && cascaderState.selectedDistricts.has(district.id)
        ).length;
        
        const totalDistrictCount = city.children.length;
        const hasAnyDistrictSelected = selectedDistrictCount > 0;
        const isFullySelected = isCitySelected && selectedDistrictCount === totalDistrictCount;
        
        console.log(`城市 ${city.name} 状态: 城市选中=${isCitySelected}, 区县选中=${selectedDistrictCount}/${totalDistrictCount}`);
        
        if (isFullySelected) {
            // 当前是完全选中状态（城市+所有区县），切换为只选择城市
            console.log(`切换为只选择城市: ${city.name}`);
            cascaderState.selectedCities.add(city.id);
            
            // 取消选择所有子级区县
            city.children.forEach(district => {
                if (district && district.id) {
                    cascaderState.selectedDistricts.delete(district.id);
                }
            });
        } else if (isCitySelected && !hasAnyDistrictSelected) {
            // 当前只选择了城市（无区县），取消城市选择
            console.log(`取消选择城市: ${city.name}`);
            cascaderState.selectedCities.delete(city.id);
        } else if (isCitySelected && hasAnyDistrictSelected) {
            // 城市已选中且有部分区县选中，取消全部选择
            console.log(`取消选择城市及所有区县: ${city.name}`);
            cascaderState.selectedCities.delete(city.id);
            
            // 取消选择所有子级区县
            city.children.forEach(district => {
                if (district && district.id) {
                    cascaderState.selectedDistricts.delete(district.id);
                }
            });
        } else {
            // 城市未选中，首次选择：只选择城市本身
            console.log(`首次选择城市: ${city.name}`);
            cascaderState.selectedCities.add(city.id);
            // 不自动选择子级区县
        }
        
        // 检查省份状态
        updateProvinceStatus(province);
        updateSelectedAreaIds();
        console.log('城市选择完成，已选区域数量:', getSelectedAreaTags().length);
    };

    /**
     * 切换区县选择
     */
    const toggleDistrictSelection = (district, city, province) => {
        console.log('toggleDistrictSelection triggered:', district?.name, 'in', city?.name, province?.name);
        
        // 添加安全检查
        if (!district || !district.id || !city || !city.id || !province || !province.id) {
            console.error('无效的区县、城市或省份数据:', district, city, province);
            return;
        }
        
        const isSelected = cascaderState.selectedDistricts.has(district.id);
        console.log('District selection before:', isSelected, 'for', district.name);
        
        if (isSelected) {
            cascaderState.selectedDistricts.delete(district.id);
            console.log('District deselected:', district.name);
        } else {
            cascaderState.selectedDistricts.add(district.id);
            console.log('District selected:', district.name);
        }
        
        // 检查城市和省份状态
        updateCityStatus(city);
        updateProvinceStatus(province);
        updateSelectedAreaIds();
        
        console.log('District selection after:', cascaderState.selectedDistricts.has(district.id), 'for', district.name);
    };
    
    /**
     * 双击选择省份及所有子级
     */
    const selectProvinceAndAllChildren = (province) => {
        console.log('🚀 [DOUBLE-CLICK] 选择省份及所有子级:', province?.name);
        
        if (!province || !province.id || !province.children) {
            console.error('无效的省份数据:', province);
            return;
        }
        
        // 选择省份
        cascaderState.selectedProvinces.add(province.id);
        
        // 选择所有子级城市和区县
        province.children.forEach(city => {
            if (city && city.id) {
                cascaderState.selectedCities.add(city.id);
                if (city.children) {
                    city.children.forEach(district => {
                        if (district && district.id) {
                            cascaderState.selectedDistricts.add(district.id);
                        }
                    });
                }
            }
        });
        
        updateSelectedAreaIds();
        console.log('省份全选完成，已选区域数量:', getSelectedAreaTags().length);
    };
    
    /**
     * 双击选择城市及所有区县
     */
    const selectCityAndAllDistricts = (city, province) => {
        console.log('🚀 [DOUBLE-CLICK] 选择城市及所有区县:', city?.name);
        
        if (!city || !city.id || !city.children) {
            console.error('无效的城市数据:', city);
            return;
        }
        
        // 选择城市
        cascaderState.selectedCities.add(city.id);
        
        // 选择所有子级区县
        city.children.forEach(district => {
            if (district && district.id) {
                cascaderState.selectedDistricts.add(district.id);
            }
        });
        
        // 检查省份状态
        if (province) {
            updateProvinceStatus(province);
        }
        updateSelectedAreaIds();
        console.log('城市全选完成，已选区域数量:', getSelectedAreaTags().length);
    };

    /**
     * 更新省份选择状态
     */
    const updateProvinceStatus = (province) => {
        const selectedCityCount = province.children.filter(city => 
            cascaderState.selectedCities.has(city.id)
        ).length;
        
        // 检查省份下是否还有选中的区县
        const hasSelectedDistrictInProvince = province.children.some(city => 
            city && city.children && city.children.some(district => 
                district && district.id && cascaderState.selectedDistricts.has(district.id)
            )
        );
        
        // 只有在省份下既没有选中的城市，也没有选中的区县时，才取消省份选择
        if (selectedCityCount === 0 && !hasSelectedDistrictInProvince) {
            cascaderState.selectedProvinces.delete(province.id);
        } else if (selectedCityCount === province.children.length) {
            // 如果所有城市都被选中，则选中省份
            cascaderState.selectedProvinces.add(province.id);
        }
        // 其他情况（部分选中）保持省份选择状态不变
    };

    /**
     * 更新城市选择状态
     */
    const updateCityStatus = (city) => {
        const selectedDistrictCount = city.children.filter(district => 
            cascaderState.selectedDistricts.has(district.id)
        ).length;
        
        if (selectedDistrictCount === 0) {
            cascaderState.selectedCities.delete(city.id);
        } else if (selectedDistrictCount === city.children.length) {
            cascaderState.selectedCities.add(city.id);
        }
    };

    /**
     * 更新选中的区域ID列表
     */
    const updateSelectedAreaIds = () => {
        const selectedIds = [];
        
        // 添加选中的省份
        cascaderState.selectedProvinces.forEach(id => selectedIds.push(id));
        
        // 添加选中的城市
        cascaderState.selectedCities.forEach(id => selectedIds.push(id));
        
        // 添加选中的区县
        cascaderState.selectedDistricts.forEach(id => selectedIds.push(id));
        
        batchMappingForm.areaIds = selectedIds;
        mappingForm.areaId = selectedIds.length > 0 ? selectedIds[0] : '';
    };

    /**
     * 获取选中区域的显示标签
     */
    const getSelectedAreaTags = () => {
        const tags = [];
        
        cascaderState.selectedProvinces.forEach(provinceId => {
            const province = (areaTree.value || []).find(p => p.id === provinceId);
            if (province) {
                tags.push({
                    id: provinceId,
                    text: province.name,
                    type: 'province'
                });
            }
        });
        
        cascaderState.selectedCities.forEach(cityId => {
            const city = findCityById(cityId);
            if (city && city.province) {
                tags.push({
                    id: cityId,
                    text: `${city.province.name} > ${city.name}`,
                    type: 'city'
                });
            }
        });
        
        cascaderState.selectedDistricts.forEach(districtId => {
            const district = findDistrictById(districtId);
            if (district && district.city && district.province) {
                tags.push({
                    id: districtId,
                    text: `${district.province.name} > ${district.city.name} > ${district.name}`,
                    type: 'district'
                });
            }
        });
        
        return tags;
    };

    /**
     * 根据ID查找城市
     */
    const findCityById = (cityId) => {
        for (const province of areaTree.value) {
            const city = province.children.find(c => c.id === cityId);
            if (city) {
                return { ...city, province };
            }
        }
        return null;
    };

    /**
     * 根据ID查找区县
     */
    const findDistrictById = (districtId) => {
        for (const province of areaTree.value) {
            for (const city of province.children) {
                const district = city.children.find(d => d.id === districtId);
                if (district) {
                    return { ...district, city, province };
                }
            }
        }
        return null;
    };

    /**
     * 删除选中的区域标签
     */
    const removeSelectedAreaTag = (tagId, tagType) => {
        if (tagType === 'province') {
            const province = (areaTree.value || []).find(p => p.id === tagId);
            if (province) {
                toggleProvinceSelection(province);
            }
        } else if (tagType === 'city') {
            const cityInfo = findCityById(tagId);
            if (cityInfo) {
                toggleCitySelection(cityInfo, cityInfo.province);
            }
        } else if (tagType === 'district') {
            const districtInfo = findDistrictById(tagId);
            if (districtInfo) {
                toggleDistrictSelection(districtInfo, districtInfo.city, districtInfo.province);
            }
        }
    };

    /**
     * 切换省份展开状态
     */
    const toggleProvinceExpansion = (province) => {
        if (cascaderState.expandedProvinces.has(province.id)) {
            cascaderState.expandedProvinces.delete(province.id);
        } else {
            cascaderState.expandedProvinces.add(province.id);
        }
    };

    /**
     * 切换城市展开状态
     */
    const toggleCityExpansion = (city) => {
        if (cascaderState.expandedCities.has(city.id)) {
            cascaderState.expandedCities.delete(city.id);
        } else {
            cascaderState.expandedCities.add(city.id);
        }
    };

    /**
     * 检查省份是否为半选中状态
     */
    const isProvinceIndeterminate = (province) => {
        if (!province || !province.children || province.children.length === 0) {
            return false;
        }
        
        // 检查省份是否已选中
        const isProvinceSelected = cascaderState.selectedProvinces.has(province.id);
        
        // 统计选中的城市数量
        const selectedCityCount = province.children.filter(city => 
            cascaderState.selectedCities.has(city.id)
        ).length;
        
        // 统计选中的区县数量
        let selectedDistrictCount = 0;
        let totalDistrictCount = 0;
        province.children.forEach(city => {
            if (city.children) {
                totalDistrictCount += city.children.length;
                selectedDistrictCount += city.children.filter(district => 
                    cascaderState.selectedDistricts.has(district.id)
                ).length;
            }
        });
        
        // 如果省份已选中且所有城市都选中，则不是半选中
        if (isProvinceSelected && selectedCityCount === province.children.length && selectedDistrictCount === totalDistrictCount) {
            return false;
        }
        
        // 如果有部分城市选中或部分区县选中，则为半选中
        const hasPartialSelection = selectedCityCount > 0 || selectedDistrictCount > 0;
        const hasFullSelection = selectedCityCount === province.children.length && selectedDistrictCount === totalDistrictCount;
        
        return hasPartialSelection && !hasFullSelection;
    };

    /**
     * 检查城市是否为半选中状态
     */
    const isCityIndeterminate = (city) => {
        if (!city || !city.children || city.children.length === 0) {
            return false;
        }
        
        // 检查城市是否已选中
        const isCitySelected = cascaderState.selectedCities.has(city.id);
        
        // 统计选中的区县数量
        const selectedDistrictCount = city.children.filter(district => 
            district && district.id && cascaderState.selectedDistricts.has(district.id)
        ).length;
        
        // 如果城市已选中且所有区县都选中，则不是半选中
        if (isCitySelected && selectedDistrictCount === city.children.length) {
            return false;
        }
        
        // 如果有部分区县选中，则为半选中
        const hasPartialSelection = selectedDistrictCount > 0;
        const hasFullSelection = selectedDistrictCount === city.children.length;
        
        return hasPartialSelection && !hasFullSelection;
    };

    /**
     * 全选/取消全选所有省份
     */
    const toggleSelectAllProvinces = () => {
        const allSelected = (areaTree.value || []).every(province => 
            cascaderState.selectedProvinces.has(province.id)
        );
        
        if (allSelected) {
            // 取消全选
            (areaTree.value || []).forEach(province => {
                cascaderState.selectedProvinces.delete(province.id);
                // 同时取消该省份下所有城市和区县的选中
                if (province.children) {
                    province.children.forEach(city => {
                        cascaderState.selectedCities.delete(city.id);
                        if (city.children) {
                            city.children.forEach(district => {
                                cascaderState.selectedDistricts.delete(district.id);
                            });
                        }
                    });
                }
            });
        } else {
            // 全选
            (areaTree.value || []).forEach(province => {
                cascaderState.selectedProvinces.add(province.id);
                // 同时选中该省份下所有城市和区县
                if (province.children) {
                    province.children.forEach(city => {
                        cascaderState.selectedCities.add(city.id);
                        if (city.children) {
                            city.children.forEach(district => {
                                cascaderState.selectedDistricts.add(district.id);
                            });
                        }
                    });
                }
            });
        }
        
        updateSelectedAreaIds();
        console.log('全选省份切换:', allSelected ? '取消全选' : '全选');
    };
    
    /**
     * 全选/取消全选当前展开省份的所有城市
     */
    const toggleSelectAllCities = () => {
        const expandedProvinces = (areaTree.value || []).filter(province => 
            cascaderState.expandedProvinces.has(province.id)
        );
        
        if (expandedProvinces.length === 0) {
            window.showMessage('请先展开省份', true);
            return;
        }
        
        const allExpandedCities = [];
        expandedProvinces.forEach(province => {
            if (province.children) {
                allExpandedCities.push(...province.children);
            }
        });
        
        const allSelected = allExpandedCities.every(city => 
            cascaderState.selectedCities.has(city.id)
        );
        
        if (allSelected) {
            // 取消全选
            allExpandedCities.forEach(city => {
                cascaderState.selectedCities.delete(city.id);
                if (city.children) {
                    city.children.forEach(district => {
                        cascaderState.selectedDistricts.delete(district.id);
                    });
                }
            });
        } else {
            // 全选
            allExpandedCities.forEach(city => {
                cascaderState.selectedCities.add(city.id);
                if (city.children) {
                    city.children.forEach(district => {
                        cascaderState.selectedDistricts.add(district.id);
                    });
                }
            });
        }
        
        updateSelectedAreaIds();
        console.log('全选城市切换:', allSelected ? '取消全选' : '全选');
    };
    
    /**
     * 全选/取消全选当前展开城市的所有区县
     */
    const toggleSelectAllDistricts = () => {
        const expandedCities = [];
        (areaTree.value || []).forEach(province => {
            if (province.children) {
                province.children.forEach(city => {
                    if (cascaderState.expandedCities.has(city.id)) {
                        expandedCities.push(city);
                    }
                });
            }
        });
        
        if (expandedCities.length === 0) {
            window.showMessage('请先展开城市', true);
            return;
        }
        
        const allExpandedDistricts = [];
        expandedCities.forEach(city => {
            if (city.children) {
                allExpandedDistricts.push(...city.children);
            }
        });
        
        const allSelected = allExpandedDistricts.every(district => 
            cascaderState.selectedDistricts.has(district.id)
        );
        
        if (allSelected) {
            // 取消全选
            allExpandedDistricts.forEach(district => {
                cascaderState.selectedDistricts.delete(district.id);
            });
        } else {
            // 全选
            allExpandedDistricts.forEach(district => {
                cascaderState.selectedDistricts.add(district.id);
            });
        }
        
        updateSelectedAreaIds();
        console.log('全选区县切换:', allSelected ? '取消全选' : '全选');
    };
    
    /**
     * 检查所有省份是否已全选
     */
    const isAllProvincesSelected = () => {
        return (areaTree.value || []).length > 0 && (areaTree.value || []).every(province => 
            cascaderState.selectedProvinces.has(province.id)
        );
    };
    
    /**
     * 检查当前展开的所有城市是否已全选
     */
    const isAllExpandedCitiesSelected = () => {
        const expandedProvinces = (areaTree.value || []).filter(province => 
            cascaderState.expandedProvinces.has(province.id)
        );
        
        if (expandedProvinces.length === 0) return false;
        
        const allExpandedCities = [];
        expandedProvinces.forEach(province => {
            if (province.children) {
                allExpandedCities.push(...province.children);
            }
        });
        
        return allExpandedCities.length > 0 && allExpandedCities.every(city => 
            cascaderState.selectedCities.has(city.id)
        );
    };
    
    /**
     * 检查当前展开的所有区县是否已全选
     */
    const isAllExpandedDistrictsSelected = () => {
        const expandedCities = [];
        (areaTree.value || []).forEach(province => {
            if (province.children) {
                province.children.forEach(city => {
                    if (cascaderState.expandedCities.has(city.id)) {
                        expandedCities.push(city);
                    }
                });
            }
        });
        
        if (expandedCities.length === 0) return false;
        
        const allExpandedDistricts = [];
        expandedCities.forEach(city => {
            if (city.children) {
                allExpandedDistricts.push(...city.children);
            }
        });
        
        return allExpandedDistricts.length > 0 && allExpandedDistricts.every(district => 
            cascaderState.selectedDistricts.has(district.id)
        );
    };
    
    /**
     * 清空所有选择
     */
    const clearAllSelections = () => {
        cascaderState.selectedProvinces.clear();
        cascaderState.selectedCities.clear();
        cascaderState.selectedDistricts.clear();
        updateSelectedAreaIds();
    };

    /**
     * 删除单个映射
     */
    const deleteMapping = async (id) => {
        if (!confirm('确定要删除这个映射吗？')) return;

        try {
            const result = await window.FreightApp.api.deleteMapping(id);
            if (result.code === 0) {
                window.showMessage('删除成功');
                loadMappings();
                if (selectedMappingStrategyId.value) {
                    loadMappingDetails();
                }
            } else {
                window.showMessage(result.msg || '删除失败', true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        }
    };

    /**
     * 获取映射状态文本
     */
    const getMappingStatusText = (status) => {
        return status === 1 ? '激活' : '非激活';
    };

    /**
     * 获取映射状态类
     */
    const getMappingStatusClass = (status) => {
        return status === 1 ? 'mapping-status active' : 'mapping-status inactive';
    };

    /**
     * 切换显示模式
     */
    const switchDisplayMode = (mode) => {
        displayMode.value = mode;
        console.log('切换显示模式为:', mode);
        
        // 如果切换到按区域显示模式，且数据为空，则重新加载
        if (mode === 'by-area' && mappingGroupByAreaData.value.length === 0 && selectedMappingStrategyId.value) {
            loadMappingDetails();
        }
    };

    /**
     * 编辑区域重量规则
     */
    const editAreaWeightRule = (areaId, ruleId) => {
        console.log('编辑区域重量规则:', { areaId, ruleId });
        // TODO: 实现编辑逻辑
        window.showMessage('编辑功能待实现');
    };

    /**
     * 删除区域重量规则
     */
    const deleteAreaWeightRule = async (mappingId) => {
        if (!confirm('确定要删除这个映射关系吗？')) return;

        try {
            const result = await window.FreightApp.api.deleteMapping(mappingId);
            if (result.code === 0) {
                window.showMessage('删除成功');
                // 重新加载映射详情
                if (selectedMappingStrategyId.value) {
                    loadMappingDetails();
                }
            } else {
                window.showMessage(result.msg || '删除失败', true);
            }
        } catch (err) {
            window.showMessage(err.message, true);
        }
    };

    return {
        // State
        mappings,
        submitting,
        showAddMappingModal,
        showBatchMappingModal,
        selectedMappingStrategyId,
        mappingWeightRules,
        mappingAreaDetails,
        mappingMergedData,
        mappingGroupByAreaData, // 新增：按区域分组数据
        displayMode, // 新增：显示模式
        filteredAssignments,
        selectedAssignment,
        filteredWeightRules,
        batchWeightRules,
        mappingForm,
        batchMappingForm,
        cascaderState,
        areaTree,
        isLoadingAreas,
        areaLoadRetryCount,
        
        // 联动功能相关状态
        isLinkageEnabled: cascaderState.isLinkageEnabled,
        
        // Methods
        loadMappings,
        loadMappingDetails,
        loadWeightRulesForMapping,
        loadWeightRulesForBatch,
        selectAssignment,
        addMapping,
        submitMapping,
        addBatchMappings,
        submitBatchMapping,
        deleteMapping,
        deleteMappingRuleForAreas,
        switchDisplayMode, // 新增：切换显示模式
        editAreaWeightRule, // 新增：编辑区域重量规则
        deleteAreaWeightRule, // 新增：删除区域重量规则
        closeMappingModal,
        closeBatchMappingModal,
        resetMappingForm,
        resetBatchMappingForm,
        validateMappingForm,
        validateBatchMappingForm,
        getWeightRuleName,
        getMappingStatusText,
        getMappingStatusClass,
        
        // 联动功能相关方法
        toggleLinkage,
        
        // 三级联动方法
        buildAreaTree,
        toggleProvinceSelection,
        toggleCitySelection,
        toggleDistrictSelection,
        toggleProvinceExpansion,
        toggleCityExpansion,
        getSelectedAreaTags,
        removeSelectedAreaTag,
        clearAllSelections,
        isProvinceIndeterminate,
        isCityIndeterminate,
        
        // 全选功能
        toggleSelectAllProvinces,
        toggleSelectAllCities,
        toggleSelectAllDistricts,
        isAllProvincesSelected,
        isAllExpandedCitiesSelected,
        isAllExpandedDistrictsSelected
    };
}